package com.langfeiyes.test.event;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 简单事件广播器
 */
public class SimpleEventMulticaster  implements EventMulticaster{

    //key：事件对象字节码
    //value：响应事件的监听器
    private Map<Class, List<EventListener>> map = new HashMap<>();

    @Override
    public void multicastEvent(AbstractEvent event) {
        List<EventListener> eventListeners = map.get(event.getClass());
        if (eventListeners != null){
            for (EventListener eventListener : eventListeners) {
                eventListener.onEvent(event);
            }
        }
    }
    @Override
    public void registListener(EventListener listener) {
        ParameterizedType type = (ParameterizedType) listener.getClass().getGenericInterfaces()[0];
        Class<?> eventType = (Class<?>) type.getActualTypeArguments()[0];

        List<EventListener> listeners = map.get(eventType);
        if(listeners == null){
            listeners = new ArrayList<EventListener>();
            map.put(eventType, listeners);
        }
        listeners.add(listener);
    }
    @Override
    public void removeListener(EventListener listener) {
        ParameterizedType type = (ParameterizedType) listener.getClass().getGenericInterfaces()[0];
        Type eventType = type.getActualTypeArguments()[0];
        List<EventListener> listeners = map.get(eventType.getClass());
        listeners.remove(listener);
    }
}
